import router, { asyncRoutes } from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'
const whiteList = ['/login', '/404', 'abc']
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  const token = store.state.user.token
  if (token) {
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      if (!store.getters.userId) {
        const res = await store.dispatch('user/getProFile')
        console.log(res)
        console.log(res.roles.menus, asyncRoutes)
        // 动态生成当前用户能访问的页面
        // asyncRoutes一共有8个页面，根据用户提供的权限信息，从asyncRoutes中选出当前用户能访问的页面
        const filteredRouters = asyncRoutes.filter(item => {
          return res.roles.menus.includes(item.children[0].name)
        })
        console.log(filteredRouters)
        // 补充404，在文章末尾
        filteredRouters.push({ path: '*', redirect: '/404', hidden: true })
        // 1.渲染左侧菜单
        store.commit('menu/setMenu', filteredRouters)
        // 2.添加到路由配置
        router.addRoutes(filteredRouters)
        next(to)
      }
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})
router.beforeEach((to, from, next) => {
  document.title = getPageTitle(to.meta.title)
  next()
})
router.afterEach(() => NProgress.done())
